import { ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import "@amap/amap-jsapi-types";

import type { IPoi } from "@/common/MapTypes";
import { amapInitCompuleted } from "@/bus";

export default function useInit(rootId: string) {
  /**
   * map 实例
   */
  const mapInstenceRef = ref<AMap.Map | null>(null);
  /**
   * map 构造对象
   */
  const AMapFactoryRef = ref<AMap.Map | null>(null);

  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-ignore
  window._AMapSecurityConfig = {
    securityJsCode: import.meta.env.VITE_AMAP_SECURTY_CODE,
  };

  /**
   * 加载高德地图
   */
  AMapLoader.load({
    key: import.meta.env.VITE_AMAP_KEY,
    version: import.meta.env.VITE_AMAP_JS_API_VERSION,
    plugins: ["AMap.PlaceSearch", "AMap.ToolBar"],
  }).then((AMapConstructors) => {
    AMapFactoryRef.value = AMapConstructors;

    mapInstenceRef.value = new AMapConstructors.Map(rootId, {
      viewMode: "2D", //默认使用 2D 模式
      zoom: 5, //地图级别
      //center: [116.397428, 39.90923], //地图中心点
    });

    // const toolbar = new AMapConstructors.ToolBar({
    //   position: {
    //     bottom: "180px",
    //     right: "10px",
    //   },
    // }); //创建工具条插件实例
    // mapInstenceRef.value?.addControl(toolbar); //添加工具条插件到页面

    uni.$emit(amapInitCompuleted);
  });

  /**
   * 设置地图中心点
   * @param e
   */
  function setCenter(e: IPoi) {
    mapInstenceRef.value?.setCenter([e.longitude, e.latitude], true);
  }

  function setFitView() {
    mapInstenceRef.value?.setFitView();
  }

  return {
    mapInstenceRef,
    AMapFactoryRef,
    setCenter,
    setFitView,
  };
}
